import React, { Component } from 'react';
//标签页
import { Tabs, Select, DatePicker, Button, Icon, Input, message } from 'antd';
import moment from 'moment';
//中文设置
import 'moment/locale/zh-cn';
//样式
import "../assets/css/suggestionBack.css";

import { feedbackList, feedbackIsConllection } from "../assets/js/api";


const { RangePicker } = DatePicker;
const TabPane = Tabs.TabPane;
const Option = Select.Option;


//用户反馈大容器
class suggestionBack extends Component {
    msgType(key) {
        console.log(key);
    };

    render() {
        return (
            <div className="msg">
                <div className="title">
                    消息管理
                </div>
                <Tabs defaultActiveKey="1" onChange={this.msgType}>
                    <TabPane tab="全部消息" key="1">
                        <AllMsg></AllMsg>
                    </TabPane>
                    <TabPane tab="已收藏的消息" key="2">
                        <ColllectedMsg></ColllectedMsg>
                    </TabPane>
                </Tabs>,
            </div>
        );
    }
}

function timeToStr(time) {
    //当时的时间信息
    let timeDate = new Date(time);
    let year = timeDate.getFullYear();
    let month = timeDate.getMonth() + 1;
    let date = timeDate.getDate();
    let hour = timeDate.getHours();
    let min = timeDate.getMinutes();

    //现在的时间信息
    let nowTime = new Date();
    let nowYear = nowTime.getFullYear();
    let nowMonth = nowTime.getMonth() + 1;
    let nowDate = nowTime.getDate();
    switch (true) {
        case ((nowYear === year) && (nowMonth === month) && (nowDate === date)):
            return (hour + ":" + min);
            break;
        case ((nowYear === year) && (nowMonth === month) && ((nowDate - date) === 1)):
            return ("昨天" + hour + ":" + min);
            break;
        case ((nowYear === year) && (nowMonth === month) && ((nowDate - date) === 2)):
            return ("前天" + hour + ":" + min);
            break;
        default:
            return (year + "-" + month + "-" + date + " " + hour + ":" + min);
    }
}

var initTime = getBackTime(7);

function getBackTime(times) {
    let time = new Date();
    let endTime = time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate();
    time.setDate(time.getDate() - times);
    let startTime = time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate();
    return [startTime, endTime]
}

class AllMsg extends Component {
    changeTimeType(value) {
        console.log(value);
        let duration = getBackTime(value);
        let currTime = new Date();
        let hours = currTime.getHours() > 10 ? currTime.getHours() : '0' + currTime.getHours();
        let minutes = currTime.getMinutes() > 10 ? currTime.getMinutes() : '0' + currTime.getMinutes();
        let second = currTime.getSeconds() > 10 ? currTime.getSeconds() : '0' + currTime.getSeconds();
        let current = ' ' + hours + ':' + minutes + ':' + second;
        this.setState({
            endTime: duration[1] + current,
            startTime: duration[0] + ' 00:00:00',
            currentPage: 1
        }, () => {
            console.log(111111);

            this.getSuccesstions();
        })
    };

    disabledDate(current) {
        // 选择今天以前的
        return current && current > moment().endOf('day');
    }

    changeTime = (value, time) => {
        let endTime = time[1];
        let startTime = time[0];
        this.setState({
            startTime: startTime + ' 00:00:00',
            endTime: endTime + ' 23:59:59',
            currentPage: 1
        }, () => {
            this.getSuccesstions();
        });
    };
    getSuccesstions = () => {
        let data = {
            "startTime": this.state.startTime,
            "endTime": this.state.endTime,
            "feedbackFlag": -1,
            "pageNo": this.state.currentPage,
            "pageSize": 10
        }
        console.log(data);

        feedbackList(data).then((res) => {
            let data = res.data;
            if (!data.ifsuccess) {
                message.error(data.msg);
                return
            };
            if (data.code == 10300) {
                message.error("登陆失效");
                // window.location.href = loginPath;
                return
            }
            if (data.code == 500) {
                message.warning(data.msg);
                return
            }
            if (data.code == 200) {
                let result = data.result;
                console.log(result.list);

                this.setState({
                    msgItems: result.list,
                    msgNum: result.total,
                })
            }

        })
    }
    hoverImg(even) {
        even.currentTarget.src = require("../assets/img/collection-hover.png")
    }

    outImg(even) {
        even.currentTarget.src = require("../assets/img/collection-false.png")
    }

    //收藏消息
    collect(index, id) {
        let items = this.state.msgItems;

        console.log(items);
        console.log(index);
        console.log(id);
        let feedbackId = id;
        feedbackIsConllection([feedbackId]).then((res) => {
            let data = res.data;
            console.log(data);
            if (data.ifsuccess && (data.code == 200 || data.code == 201)) {
                let ifCollect = items[index].flag == 1 ? "取消收藏成功" : "收藏成功";

                items[index].flag = items[index].flag == 1 ? 2 : 1;

                message.success(ifCollect);

                this.setState({
                    msgItems: items,
                })
            }
            if (data.ifsuccess && !(data.code == 200 || data.code == 201)) {
                message.warning(data.msg);
            }
            if (!data.ifsuccess) {
                message.error("网络延时,请稍后重试");
            }
            if (data.code == 10300) {
                message.error("登陆已失效");
                // window.location.href = loginPath;
            }
        })
    }

    //分页信息
    changePages(value) {
        if (value == 0) {
            return
        }
        let added = (this.state.currentPage + value) * 1;
        let totPages = Math.ceil(this.state.msgNum / 10)
        let page = added;
        if (added > totPages) {
            page = totPages;
        }
        if (added < 1) {
            page = 1;
        }
        this.setState({
            currentPage: page,
        }, () => {
            this.getSuccesstions();
        })
    }

    //手动输入页码
    inputPages(e) {
        let added = e.target.value
        let totPages = Math.ceil(this.state.msgNum / 10)
        let page = added;
        if (added > totPages) {
            page = totPages;
        }
        if (added < 1) {
            page = 1;
        }
        this.setState({
            inputPages: page
        }, () => {
            this.getSuccesstions();
        })
    }
    componentDidMount() {
        this.getSuccesstions();
    }
    constructor(props) {
        super(props);
        this.state = {
            dateFormat: "YYYY-MM-DD",
            startTime: initTime[0] + ' 00:00:00',
            endTime: initTime[1] + ' 23:59:59',
            msgNum: 0,
            msgItems: [],
            currentPage: 1,
            inputPages: 0,
        };

        this.changeTimeType = this.changeTimeType.bind(this);
    }

    render() {
        return (
            <div className="allMsgContainer">
                <div className="timePicker">
                    <span className="timeType">
                        <Select defaultValue="7" style={{ width: 120 }} onChange={this.changeTimeType}>
                            {/* <Option value="0">全部</Option> */}
                            <Option value="7">最近七天</Option>
                            <Option value="15">最近十五天</Option>
                            <Option value="30">最近一个月</Option>
                        </Select>
                    </span>
                    <span className="timeMsg">
                        <RangePicker
                            allowClear={false}
                            value={[moment(this.state.startTime, this.state.dateFormat), moment(this.state.endTime, this.state.dateFormat)]}
                            format={this.state.dateFormat} onChange={this.changeTime} disabledDate={this.disabledDate}
                        />
                    </span>
                </div>
                <div className="msgs">
                    <p className="msgNum">全部消息({this.state.msgNum}条)</p>

                    <div className="msgItems">
                        {this.state.msgItems.map((item, index) =>
                            <div className="magItem" key={item.feedbackId}>
                                <div className="icorn">
                                    <img src={item.headPortrait || require('../assets/img/custer.png')} alt="" />
                                </div>
                                <div className="msgInfo">
                                    <p className="phoneNum">
                                        {item.phone}
                                    </p>
                                    <p className="magText">
                                        {item.content}
                                    </p>
                                </div>
                                <div className="msgTime">
                                    <p>
                                        {timeToStr(item.createTime)}
                                    </p>
                                </div>
                                <div className="collectMsg">
                                    {item.flag == 1 ? <img src={require("../assets/img/collection-true.png")}
                                        onClick={() => this.collect(index, item.feedbackId)}
                                        alt="取消收藏" /> :
                                        <img src={require("../assets/img/collection-false.png")}
                                            onClick={() => this.collect(index, item.feedbackId)}
                                            onMouseEnter={(e) => this.hoverImg(e)}
                                            onMouseLeave={(e) => this.outImg(e)} alt="收藏" />}
                                </div>
                            </div>)}
                    </div>
                    {/*消息数目大于10时有分页*/}
                    {this.state.msgNum > 10 && <div className="pageNum">
                        <div className="btnGroup">
                            <Button className="changePage" onClick={() => this.changePages(-1)} size="small"
                                disabled={this.state.currentPage == 1}><Icon type="caret-left" /></Button>
                            <p className="pageInfo">
                                <span className="currentPage">{this.state.currentPage}</span>
                                /
                                <span className="totalPages">
                                    {Math.ceil(this.state.msgNum / 10)}
                                </span>
                            </p>
                            <Button className="changePage" size="small" onClick={() => this.changePages(+1)}
                                disabled={this.state.currentPage == Math.ceil(this.state.msgNum / 10)}><Icon
                                    type="caret-right" /></Button>
                            <Input size="small" ref="pageNum" placeholder={this.state.currentPage}
                                onChange={(e) => this.inputPages(e)} />
                            <Button className="isChangePages" size="small"
                                onClick={() => this.changePages(this.state.inputPages - this.state.currentPage)}>确定</Button>
                        </div>
                    </div>}
                </div>
            </div>
        )
    }
}

class ColllectedMsg extends Component {
    changeTimeType(value) {
        console.log(value);
        let duration = getBackTime(value);
        let currTime = new Date();
        let hours = currTime.getHours() > 10 ? currTime.getHours() : '0' + currTime.getHours();
        let minutes = currTime.getMinutes() > 10 ? currTime.getMinutes() : '0' + currTime.getMinutes();
        let second = currTime.getSeconds() > 10 ? currTime.getSeconds() : '0' + currTime.getSeconds();
        let current = ' ' + hours + ':' + minutes + ':' + second;
        this.setState({
            endTime: duration[1] + current,
            startTime: duration[0] + ' 00:00:00',
            currentPage: 1
        }, () => {
            this.getSuccesstions();
        })
    };

    disabledDate(current) {
        // 选择今天以前的
        return current && current > moment().endOf('day');
    }

    changeTime = (value, time) => {
        let endTime = time[1];
        let startTime = time[0];
        this.setState({
            startTime: startTime + ' 00:00:00',
            endTime: endTime + ' 23:59:59',
            currentPage: 1
        }, () => {
            this.getSuccesstions();
        });
    };
    getSuccesstions = () => {
        let data = {
            "startTime": this.state.startTime,
            "endTime": this.state.endTime,
            "feedbackFlag": 1,
            "pageNo": this.state.currentPage,
            "pageSize": 10
        }
        console.log(data);

        feedbackList(data).then((res) => {
            let data = res.data;
            if (!data.ifsuccess) {
                message.error(data.msg);
                return
            };
            if (data.code == 10300) {
                message.error("登陆失效");
                // window.location.href = loginPath;
                return
            }
            if (data.code == 500) {
                message.warning(data.msg);
                return
            }
            if (data.code == 200) {
                let result = data.result;
                console.log(result.list);

                this.setState({
                    msgItems: result.list,
                    msgNum: result.total,
                })
            }

        })
    }
    hoverImg(even) {
        even.currentTarget.src = require("../assets/img/collection-hover.png")
    }

    outImg(even) {
        even.currentTarget.src = require("../assets/img/collection-false.png")
    }

    //收藏消息
    collect(index, id) {
        let items = this.state.msgItems;

        console.log(items);
        console.log(index);
        console.log(id);
        let feedbackId = id;
        feedbackIsConllection([feedbackId]).then((res) => {
            let data = res.data;
            console.log(data);
            if (data.ifsuccess && (data.code == 200 || data.code == 201)) {
                let ifCollect = items[index].flag == 1 ? "取消收藏成功" : "收藏成功";

                items[index].flag = items[index].flag == 1 ? 2 : 1;

                message.success(ifCollect);

                this.setState({
                    msgItems: items,
                })
            }
            if (data.ifsuccess && !(data.code == 200 || data.code == 201)) {
                message.warning(data.msg);
            }
            if (!data.ifsuccess) {
                message.error("网络延时,请稍后重试");
            }
            if (data.code == 10300) {
                message.error("登陆已失效");
                // window.location.href = loginPath;
            }
        })
    }

    //分页信息
    changePages(value) {
        if (value == 0) {
            return
        }
        let added = (this.state.currentPage + value) * 1;
        let totPages = Math.ceil(this.state.msgNum / 10)
        let page = added;
        if (added > totPages) {
            page = totPages;
        }
        if (added < 1) {
            page = 1;
        }
        this.setState({
            currentPage: page,
        }, () => {
            this.getSuccesstions();
        })
    }

    //手动输入页码
    inputPages(e) {
        let added = e.target.value
        let totPages = Math.ceil(this.state.msgNum / 10)
        let page = added;
        if (added > totPages) {
            page = totPages;
        }
        if (added < 1) {
            page = 1;
        }
        this.setState({
            inputPages: page
        }, () => {
            this.getSuccesstions();
        })
    }
    componentDidMount() {
        this.getSuccesstions();
    }
    constructor(props) {
        super(props);
        this.state = {
            dateFormat: "YYYY-MM-DD",
            startTime: initTime[0] + ' 00:00:00',
            endTime: initTime[1] + ' 23:59:59',
            msgNum: 0,
            msgItems: [],
            currentPage: 1,
            inputPages: 0,
        };

        this.changeTimeType = this.changeTimeType.bind(this);
    }

    render() {
        return (
            <div className="allMsgContainer">
                <div className="timePicker">
                    <span className="timeType">
                        <Select defaultValue="7" style={{ width: 120 }} onChange={this.changeTimeType}>
                            {/* <Option value="0">全部</Option> */}
                            <Option value="7">最近七天</Option>
                            <Option value="15">最近十五天</Option>
                            <Option value="30">最近一个月</Option>
                        </Select>
                    </span>
                    <span className="timeMsg">
                        <RangePicker
                            allowClear={false}
                            value={[moment(this.state.startTime, this.state.dateFormat), moment(this.state.endTime, this.state.dateFormat)]}
                            format={this.state.dateFormat} onChange={this.changeTime} disabledDate={this.disabledDate}
                        />
                    </span>
                </div>
                <div className="msgs">
                    <p className="msgNum">全部消息({this.state.msgNum}条)</p>

                    <div className="msgItems">
                        {this.state.msgItems.map((item, index) =>
                            <div className="magItem" key={item.feedbackId}>
                                <div className="icorn">
                                    <img src={item.headPortrait || require('../assets/img/custer.png')} alt="" />
                                </div>
                                <div className="msgInfo">
                                    <p className="phoneNum">
                                        {item.phone}
                                    </p>
                                    <p className="magText">
                                        {item.content}
                                    </p>
                                </div>
                                <div className="msgTime">
                                    <p>
                                        {timeToStr(item.createTime)}
                                    </p>
                                </div>
                                <div className="collectMsg">
                                    {item.flag == 1 ? <img src={require("../assets/img/collection-true.png")}
                                        onClick={() => this.collect(index, item.feedbackId)}
                                        alt="取消收藏" /> :
                                        <img src={require("../assets/img/collection-false.png")}
                                            onClick={() => this.collect(index, item.feedbackId)}
                                            onMouseEnter={(e) => this.hoverImg(e)}
                                            onMouseLeave={(e) => this.outImg(e)} alt="收藏" />}
                                </div>
                            </div>)}
                    </div>
                    {/*消息数目大于10时有分页*/}
                    {this.state.msgNum > 10 && <div className="pageNum">
                        <div className="btnGroup">
                            <Button className="changePage" onClick={() => this.changePages(-1)} size="small"
                                disabled={this.state.currentPage == 1}><Icon type="caret-left" /></Button>
                            <p className="pageInfo">
                                <span className="currentPage">{this.state.currentPage}</span>
                                /
                                <span className="totalPages">
                                    {Math.ceil(this.state.msgNum / 10)}
                                </span>
                            </p>
                            <Button className="changePage" size="small" onClick={() => this.changePages(+1)}
                                disabled={this.state.currentPage == Math.ceil(this.state.msgNum / 10)}><Icon
                                    type="caret-right" /></Button>
                            <Input size="small" ref="pageNum" placeholder={this.state.currentPage}
                                onChange={(e) => this.inputPages(e)} />
                            <Button className="isChangePages" size="small"
                                onClick={() => this.changePages(this.state.inputPages - this.state.currentPage)}>确定</Button>
                        </div>
                    </div>}
                </div>
            </div>
        )
    }
}

export default suggestionBack;

